package weaver.formmode.interfaces.impl.huangwm.SW003;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.customization.huangwm.dao.SW003.AssetInfoOperationDao;
import com.api.customization.huangwm.dao.SW003.LoggingDao;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.HttpRequest;
import com.customization.huangwm.utils.LogTool;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.file.ExcelParseForPOI;
import weaver.formmode.interfaces.ImportPreInterfaceForPOIAction;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.system.SysRemindWorkflow;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;

/**
 * @Author Huangwm
 * @Date 2022-05-05
 * @Version 1.0
 * @Description TODO 物料导入前执行检查并提交数据至用友
 **/
public class ImportAssetBeforeAction implements ImportPreInterfaceForPOIAction {
    private LogTool logTool = new LogTool("/log/SW003/huangwm/model/action/ImportAssetBeforeAcion", false);
    private DBTools dbTools = new DBTools();
    private DateTools dateTools = new DateTools();
    //private LoggingDao loggingDao = new LoggingDao();

    @Override
    public String checkImportData(Map<String, Object> param, User user, ExcelParseForPOI excel) {
        // 获取模块ID
        Integer modeId = Util.getIntValue(param.get("modeid").toString());
        //表单id
        Integer formId = Util.getIntValue(param.get("formid").toString());
        // 获取当前登录人员ID
        Integer userId = user.getUID();
        logTool.writeLog("物料导入前执行校验---");
        Workbook workbook = excel.getWb();
        Sheet sheet = workbook.getSheetAt(0);
        //获取最后一行的num，即总行数。此处从0开始计数
        int maxRow = sheet.getLastRowNum();
        List<List<String>> Excel_datas = new ArrayList<>();
        List<String> codes = new ArrayList<>();//單獨存放物料編碼
        BaseBean baseBean = new BaseBean();
        String eop_reqUrl = baseBean.getPropValue("SW003", "eop_reqUrl");
        if (eop_reqUrl.isEmpty()) {
            return "獲取SW003.peoperties中的eop_reqUrl爲空";
        }
        String eop_reqToken = baseBean.getPropValue("SW003", "eop_reqToken");
        if (eop_reqToken.isEmpty()) {
            return "獲取SW003.peoperties中的eop_reqToken爲空";
        }

        if (!(sheet.getRow(0).getCell(1) + "").equals("物料編碼")) {
            return "Excel模板格式錯誤,第二列應為物料編碼,現為[" + sheet.getRow(0).getCell(1) + "]";
        }
        byte[] space = new byte[] {(byte) 0xc2, (byte) 0xa0};
        try{
            for (int row = 1; row <= maxRow; row++) {
                List<String> data = new ArrayList<>();
                //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                int maxCel = sheet.getRow(row).getLastCellNum();
                logTool.writeLog("--------第" + row + "行的数据如下--------");
                for (int cel = 1; cel <= 9; cel++) {
                    //第一列和第二列是編碼和名稱 讀取是轉成字符串
                    if (cel == 1) {
                        sheet.getRow(row).getCell(cel).setCellType(CellType.STRING);
                        if (!isBlank(sheet.getRow(row).getCell(cel) + "").isEmpty()) {
                            if(validateString(sheet.getRow(row).getCell(cel)+ "")){
                                codes.add(sheet.getRow(row).getCell(cel).getStringCellValue());
                            }else{
                                return ("第" + row + "行物料編碼名稱錯誤，只允許字母、数字、空格及連字符（-）");
                            }
                        } else {
                            return ("第" + row + "行物料編碼存在空值");
                        }
                        data.add(isBlank(sheet.getRow(row).getCell(cel).getStringCellValue() + ""));
                    }else if(cel == 2){
                        sheet.getRow(row).getCell(cel).setCellType(CellType.STRING);
                        data.add(
                                isBlank(sheet.getRow(row).getCell(cel).getStringCellValue()).replace(String.valueOf((char)160)," ")
                        );
                    }else{
                        data.add(isBlank(sheet.getRow(row).getCell(cel) + ""));
                    }

                }
                Excel_datas.add(data);
                logTool.writeLog(JSON.toJSONString(data));
            }
            //logTool.writeLog(JSON.toJSONString(codes));
        }catch (Exception e){
            e.printStackTrace();
            logTool.writeLog("導入時獲取表格數據異常 "+e.getMessage());
            return ("導入時獲取表格數據異常 "+e.getMessage());
        }

        if (codes.size() > 0 && Excel_datas.size() > 0) {
            long recordid = System.currentTimeMillis();
            String check = check(codes);
            if (!check.isEmpty()) {
                return check;
            }

            RecordSet rs1 = new RecordSet();
            RecordSet rs2 = new RecordSet();
            RecordSet rs3 = new RecordSet();
            //分解数据传入用友
            Map<String, Object> reqData = new HashMap<>();
            List<Map<String, Object>> datas = new ArrayList<>();//reqData中的data
            try {
                int row = 2;
                for (List<String> value : Excel_datas) {
                    Map<String, Object> data = new HashMap<>();
                    Map<String, String> invbas = new HashMap<>();
                    Map<String, String> invman = new HashMap<>();
                    String assetCode = value.get(0);//物料編碼
                    invbas.put("id", assetCode);
                    invbas.put("invcode", assetCode);
                    String assetName = value.get(1);//物料名稱
                    invbas.put("invname", replaceStr(assetName));
                    invbas.put("forinvname", replaceStr(assetName));
                    invbas.put("invshortname", replaceStr(assetName));
                    String assetDescribe = value.get(2);//物料描述
                    invman.put("memo", replaceStr(assetDescribe));//將物料描述當作備注
                    String unit = value.get(3);//單位
                    if(unit.isEmpty()) return ("第" + row + "行單位不能爲空");
                    //前置判断填写是否有误防止导入失败
                    String unit_ = dbTools.getUnitCodeByName(rs1, unit);
                    if (unit_.indexOf("不存在") >= 0) {
                        return "第" + row + "行" + unit_;
                    }
                    invbas.put("pk_measdoc", unit_);
                    String managerDep = value.get(4);//管理部門
                    String managerDep_ = dbTools.exisManagerDep(rs3, managerDep);
                    if (managerDep_.indexOf("不存在") >= 0) {
                        return "第" + row + "行" + managerDep_;
                    }
                    String isAsset = value.get(5).trim();//是否資產
                    if(!isAsset.equals("N") && !isAsset.equals("Y") ){
                        return "第" + row + "行'是否資產'請填寫Y或N";
                    }
                    //invbas.put("asset", (isAsset.equals("Y") || isAsset.equals("是")) ? "Y" : "N");
                    invbas.put("asset", "N");
                    String assetModel = value.get(6);//型號
                    //if(assetModel.isEmpty() || assetModel.equals("")){
                    //return "第" + row + "行型號为空";
                    //}
                    invbas.put("invtype", replaceStr(assetModel));
                    String assetType = value.get(7);//EAP物料種類
                    if(assetType.isEmpty()) return ("第" + row + "行EAP物料種類不能爲空");
                    String assetType_ = dbTools.getEapTypeNameCompareYY(rs2, assetType);
                    if (assetType_.indexOf("不存在") >= 0 || assetType_.isEmpty()) {
                        return "第" + row + "行物料類型"+assetType+"不存在";
                    }
                    invbas.put("pk_invcl", assetType_);
                    /*
                    20221013 导入模板不使用库存 移除逻辑
                    Double totalquantity = Double.parseDouble(value.get(8));//总入库数量
                    Double usedQuantity = Double.parseDouble(value.get(9));//已領用數量
                    Double InventoryQuantity = Double.parseDouble(value.get(10));//庫存數量
                    if((totalquantity-usedQuantity)<0 || InventoryQuantity<0){
                        return "第" + row + "行庫存數量填寫不規範,請注意合計數不能小於0";
                    }
                    */
                    //20221013  增加默认仓库逻辑
                    String wareHouse = value.get(8);//默认仓库
                    if(wareHouse.isEmpty()) return ("第" + row + "行EAP默認倉庫不能爲空");
                    String wareHouse_ = dbTools.exisWarehouse(rs2,wareHouse);
                    if (wareHouse_.indexOf("不存在") >= 0) {
                        return "第" + row + "行" + wareHouse_;
                    }

                    //invbas其他參數
                    invbas.put("setpartsflag", "N");
                    invbas.put("invspec", "");
                    invbas.put("pk_corp", "MW");
                    invbas.put("discountflag", "N");
                    invbas.put("setpartsflag", "N");
                    invbas.put("assistunit", "N");
                    invbas.put("ismngstockbygrswt", "N");
                    invbas.put("autobalancemeas", "Y");
                    invbas.put("isstorebyconvert", "N");
                    invbas.put("isretail", "N");
                    invbas.put("pk_taxitems", "9003");
                    //invman其他參數
                    invman.put("sellproxyflag", "N");
                    invman.put("planprice", "0");
                    invman.put("costprice", "0");
                    invman.put("refsaleprice", "0");
                    invman.put("consumesettleflag", "N");
                    invman.put("qualitymanflag", "N");
                    invman.put("qualityperiodunit", "2");
                    invman.put("qualitydaynum", "0");
                    invman.put("serialmanaflag", "N");
                    invman.put("wholemanaflag", "N");
                    invman.put("sealflag", "N");//是否封存
                    invman.put("accflag", "N");
                    invman.put("outtrackin", "N");
                    invman.put("negallowed", "N");
                    invman.put("iscanpurchased", "Y");
                    invman.put("iscansold", "N");
                    invman.put("issalable", "Y");
                    invman.put("isnoconallowed", "Y");

                    data.put("invbas", invbas);
                    data.put("invman", invman);
                    datas.add(data);
                    row++;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "扩展接口获取Excel分解數據异常 " + e.toString();
            }
            String filename = "";
            String rootPath = "";
            try {
                filename = "imp_uerid_" + user.getUID() + "_" + getTimestamp() + ".xlsx";
                rootPath = GCONST.getRootPath() + "log/SW003/huangwm/model/action/ImportAssetBeforeAcion/imp/";
                File path = new File(rootPath);
                if (!path.exists()) {
                    logTool.writeLog(rootPath + " 路径不存在");
                    path.mkdirs();
                }

                logTool.writeLog("导入模板临时存储路径：" + rootPath + filename);
                OutputStream outputStream = new FileOutputStream(rootPath + filename);
                workbook.write(outputStream);//下载文件到服务器;
                outputStream.close();
                outputStream.flush();
                //生成資產物料待登記臺賬--采購入庫記錄
                /*
                Map<String, Object> result = uf_003_yyArrivalRecord(Excel_datas, rootPath + filename, recordid);
                if (!(boolean) result.get("apiStatus")) {
                    return result.get("msg").toString();
                }
                */
            } catch (Exception e) {
                e.printStackTrace();
                return "导入模板临时存储异常 " + e.toString();
            }

            reqData.put("data", datas);
            HttpRequest httpRequest = new HttpRequest();
            String times = httpRequest.getTimestamp();
            JSONObject params = new JSONObject();
            params.put("reqNb", times);
            params.put("reqLang", "zh");
            params.put("reqToken", eop_reqToken);
            params.put("reqData", reqData);
            try {
                logTool.writeLog("---傳入用友參數如下---");
                logTool.writeLog(JSON.toJSONString(params));
                JSONObject json = httpRequest.CallApiPost(eop_reqUrl + "/eop/eapToUfida/bsinvman", JSONObject.toJSONString(params));
                logTool.writeLog("---傳入用友結果如下---");
                logTool.writeLog(JSON.toJSONString(json));
                LoggingDao loggingDao = new LoggingDao();
                loggingDao.wrtieLog("0", "/eop/eapToUfida/bsinvman", "來自於EAP批量導入物料數據執行接口調用,請查看/log/SW003/huangwm/model/action/ImportAssetBeforeAcion日志", JSON.toJSONString(json));
                if(json==null || !json.getOrDefault("state","-1").equals("0") || json.getString("state").equals("-1")){
                    rs3.execute("delete from uf_003_yyArrivalRecord where poCode='" + "imp_" + recordid + "'");
                    return "扩展接口获取分解數據傳入用友失敗,結果為" + JSON.toJSONString(json);
                }else {
                    //寫入用友期初庫存
                    /* 20221013 期初对接改用仓库 移除逻辑
                    JSONObject params_Bill = new JSONObject();
                    params_Bill.put("reqNb", times);
                    params_Bill.put("reqLang", "zh");
                    params_Bill.put("reqToken", eop_reqToken);
                    Map<String, Object> reqData_Bill = new HashMap<>();
                    List<Map<String, Object>> bill = new ArrayList<>();//reqData中的bill
                    Map<String, Object> bill_data = new HashMap<>();
                    //billHead内容
                    Map<String, Object> billHead = new HashMap<>();
                    billHead.put("id",times);
                    billHead.put("cbilltypecode","4A");
                    billHead.put("dbilldate",dateTools.getCurrentDate());
                    billHead.put("pk_corp","MW");
                    billHead.put("vbillcode","");
                    billHead.put("cdispatcherid","21");
                    billHead.put("cdeptid",dbTools.getYyDepCode(user.getUID() + ""));
                    billHead.put("pk_calbody","MW");
                    billHead.put("cwarehouseid","02");
                    billHead.put("coperatorid",dbTools.getWorkCode(user.getUID()+""));
                    billHead.put("fbillflag","2");
                    billHead.put("vnote","期初-02倉庫");
                    //添加billhead内容
                    bill_data.put("billHead",billHead);

                    List<Map<String, Object>> billBody = new ArrayList<>();
                    for (List<String> value : Excel_datas) {
                        //如果導入數量大於0才插入
                        String assetCode = value.get(0);//物料編碼
                        String assetName = value.get(1);//物料名稱
                        String assetDescribe = value.get(2);//物料描述
                        String unit = value.get(3);//單位
                        String managerDep = value.get(4);//管理部門
                        String isAsset = value.get(5);//是否資產
                        String assetModel = value.get(6);//型號
                        String assetType = value.get(7);//EAP物料種類
                        Double totalquantity = Double.parseDouble(value.get(8));//总入库数量
                        Double usedQuantity = Double.parseDouble(value.get(9));//已領用數量
                        Double InventoryQuantity = Double.parseDouble(value.get(10));//庫存數量
                        if((totalquantity-usedQuantity)>0){
                            Map<String, Object> billBody_data = new HashMap<>();
                            billBody_data.put("cinventoryid",assetCode);
                            billBody_data.put("dbizdate",dateTools.getCurrentDate());
                            billBody_data.put("ninnum",(totalquantity-usedQuantity));
                            billBody_data.put("nprice","0");
                            billBody_data.put("nmny","0");
                            //添加body内容
                            billBody.add(billBody_data);
                        }

                    }
                    bill_data.put("billBody",billBody);
                    bill.add(bill_data);
                    reqData_Bill.put("bill",bill);
                    params_Bill.put("reqData",reqData_Bill);

                    logTool.writeLog("---期初入庫傳入用友參數如下---");
                    logTool.writeLog(JSON.toJSONString(params_Bill));
                    JSONObject json_Bill = httpRequest.CallApiPost(eop_reqUrl + "/eop/eapToUfida/icBillBegin", JSONObject.toJSONString(params_Bill));
                    logTool.writeLog("---期初入庫傳入用友結果如下---");
                    logTool.writeLog(JSON.toJSONString(json_Bill));
                    loggingDao.wrtieLog("0", "/eop/eapToUfida/icBillBegin", JSON.toJSONString(params_Bill), JSON.toJSONString(json_Bill));
                    if(json_Bill==null || !json_Bill.getOrDefault("state","-1").equals("0")){
                        logTool.writeLog("保存物料寫入用友成功但期初入庫失敗 " + JSON.toJSONString(json_Bill));
                        SysRemindWorkflow remind = new SysRemindWorkflow();
                        remind.make("EAP導入物料期初庫存對接失敗",
                                0, 0, 0, 0, 1,
                                dbTools.getUseridByLoginid("hel"),
                                "<span>EAP導入物料數據基礎物料檔案已傳給用友，OA保存成功，但期初庫存入库對接失敗 "+JSON.toJSONString(json_Bill)+"</span><br /><span>本次导入excel模板临时存储路径：" + rootPath + filename
                                +"; </span><br />详细看查看日志表uf_003_interfaceLog或当天"+dateTools.getCurrentDate()+"的对接日并搜索关键字："+times, 0);
                    }
                  */
                }
            } catch (Exception e) {
                rs3.execute("delete from uf_003_yyArrivalRecord where poCode='" + "imp_" + recordid + "'");
                e.printStackTrace();
                return "扩展接口获取分解數據傳入用友出現異常 " + e.toString();
            }
        } else {
            return "扩展接口获取excel數據为空";
        }
        return "";
    }

    public boolean validateString(String input) {
        String pattern = "^[A-Za-z0-9- ]+$";
        return input.matches(pattern);
    }

    public String isBlank(String str) {
        if (str.isEmpty() || str.equals("null")) return "";
        return str;
    }

    private LogTool logTool2 = new LogTool("/log/SW003/huangwm/model/action/ImportAssetBeforeAcionDBlog", false);

    /**
     * 检查本次导入的数据中是否存在相同的itemcode
     * @param codes
     * @return
     */
    public String check(List<String> codes) {
        if (codes.size() <= 0) return "物料編碼集合为空";
        RecordSet rs = new RecordSet();
        int i = 1;
        for (String code : codes) {
            logTool2.writeLog("查询物料编码是否存在："+"select id from uf_003_AssteInfo where assetCode='" + code + "'");
            rs.execute("select id from uf_003_AssteInfo where assetCode='" + code + "'");
            if (rs.next()) {
                logTool2.writeLog("第" + i + "行物料編碼"+code+"已存在");
                return "第" + i + "行物料編碼已存在";
            }
            i++;
        }
        return "";
    }

    /**
     * 将excel导入的资产数据生成到采购入库记录中
     * @param Excel_datas
     * @return
     */
    /*
    private Map<String, Object> uf_003_yyArrivalRecord_no(List<List<String>> Excel_datas, String path, long recordid,int userid) {
        Map<String, Object> result = new HashMap<>();
        result.put("apiStatus", true);
        BaseBean baseBean = new BaseBean();
        AssetInfoOperationDao dao = new AssetInfoOperationDao();
        List<Map<String, String>> datasToRecords = new ArrayList<>();
        RecordSet rs1 = new RecordSet();
        for (List<String> value : Excel_datas) {
            //如果導入數量大於0才插入
            String assetCode = value.get(0);//物料編碼
            String assetName = value.get(1);//物料名稱
            String assetDescribe = value.get(2);//物料描述
            String unit = value.get(3);//單位
            String managerDep = value.get(4);//管理部門
            String isAsset = value.get(5);//是否資產
            String assetModel = value.get(6);//型號
            String assetType = value.get(7);//EAP物料種類
            Double InventoryQuantity = Double.parseDouble(value.get(8));//总入库数量
            Double usedQuantity = Double.parseDouble(value.get(9));//已領用數量
            Double totalquantity = Double.parseDouble(value.get(10));//庫存數量

            if ((totalquantity - usedQuantity) > 0 && isAsset.equals("Y")) {
                Map<String, String> data = new HashMap<>();
                data.put("assetCode", assetCode);
                data.put("assetName", assetName);
                data.put("assetDescribe", assetDescribe);
                data.put("unit", unit);
                data.put("managerDep", managerDep);
                data.put("isAsset", isAsset);
                data.put("assetModel", assetModel);
                data.put("assetType", assetType);
                data.put("InventoryQuantity", InventoryQuantity + "");
                data.put("usedQuantity", usedQuantity + "");
                data.put("totalquantity", totalquantity + "");
                data.put("quantity", (totalquantity - usedQuantity) + "");
                datasToRecords.add(data);
            }
        }
        if (datasToRecords.size() > 0) {
            String uf_003_yyArrivalRecord_Modeid = baseBean.getPropValue("SW003", "uf_003_yyArrivalRecord_Modeid");
            String sql_0 = "insert into uf_003_yyArrivalRecord"
                    + "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID"
                    + ",eapItemCode,itemcode,assetName,assetDescribe,unit,isAsset,manageDep,assetModel,assetType,quantity,locationCode,locationDescribe"
                    + ",brand,manufacturer,FACode,FACategory,prjNo,poCode,price,arrivalDate,supplier,assetNums,thisSouce)"
                    + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            List<List<Object>> paramsList_0 = new ArrayList<>();//是资产
            List<List<Object>> paramsList_1 = new ArrayList<>();//不是资产
            List<Map<String, String>> logList = new ArrayList<>();
            for (Map<String, String> data : datasToRecords) {
                List<Object> param_0 = new ArrayList<>();
                List<Object> param_1 = new ArrayList<>();
                String assetCode = data.get("assetCode");
                String assetName = data.get("assetName"),
                        assetDescribe = data.get("assetDescribe"),
                        unit = data.get("unit"),
                        manageDep = data.getOrDefault("manageDep", ""),
                        assetModel = data.get("assetModel"),
                        assetType = data.get("assetType");
                String isAsset = data.get("isAsset");
                String quantity = data.getOrDefault("quantity", "0"),
                        locationCode = data.getOrDefault("locationCode", ""),
                        locationDescribe = data.getOrDefault("locationDescribe", ""),
                        brand = data.getOrDefault("brand", ""),
                        manufacturer = data.getOrDefault("manufacturer", ""),
                        FACode = data.getOrDefault("FACode", ""),
                        FACategory = data.getOrDefault("FACategory", ""),
                        prjNo = data.getOrDefault("prjNo", ""),
                        price = data.getOrDefault("price", ""),
                        arrivalDate = data.getOrDefault("arrivalDate", ""),
                        supplier = data.getOrDefault("supplier", "");

                Map<String, String> logMap = new HashMap();

                param_0.add(uf_003_yyArrivalRecord_Modeid);
                param_0.add(1);
                param_0.add(0);
                param_0.add(dateTools.getCurrentDate());
                param_0.add(dateTools.getCurrentTime());
                param_0.add(dateTools.getUUID());

                param_0.add(dao.getIsAsset(assetCode, "id"));
                param_0.add(assetCode);
                param_0.add(assetName);
                param_0.add(assetDescribe);
                param_0.add(dao.getAssetUnit(unit));
                param_0.add(isAsset);
                param_0.add(dbTools.getDepid(manageDep));
                param_0.add(assetModel);
                param_0.add(dbTools.getEapTypeNameCompareYY(rs1,assetType));
                param_0.add(quantity);
                param_0.add(locationCode);
                param_0.add(locationDescribe);

                param_0.add(brand);
                param_0.add(manufacturer);
                param_0.add(FACode);
                param_0.add(FACategory);
                param_0.add(prjNo);
                param_0.add("imp_" + recordid);
                param_0.add(price);
                param_0.add(arrivalDate.replace("/", "-"));
                param_0.add(supplier);
                param_0.add(0);
                param_0.add(2);

                paramsList_0.add(param_0);
            }
            RecordSetTrans rs = new RecordSetTrans();
            rs.setAutoCommit(false);
            if (paramsList_0.size() > 0) {
                try {
                    rs.executeBatchSql(sql_0, paramsList_0);
                } catch (Exception e) {
                    rs.rollback();
                    result.put("msg", "物料导入>資產物料采購入庫執行SQL異常 \n" + e.getMessage());
                    result.put("apiStatus", false);
                    loggingDao.wrtieLog("0", path, path, JSON.toJSONString(result));
                    return result;
                }
            }
            try{
                loggingDao.wrtieLog("1", path, path, JSON.toJSONString(result));
                for (int i = 0; i < logList.size(); i++) {
                    Map<String, String> log = logList.get(i);
                    loggingDao.wrtieInventoryLog(rs,"1", log.get("assetCode"),
                            Double.parseDouble(log.get("quantity")), log.get("requestNumber"), log.get("reason"),"导入初始",
                            "导入初始","0","",userid+"","","","");
                }
            }catch (Exception e){
                rs.rollback();
                result.put("msg", "物料导入记录日志异常 \n" + e.getMessage());
                result.put("apiStatus", false);
                return result;
            }

            rs.commit();
            logTool.writeLog("权限重构开始=>>>" + dateTools.getCurrentTimes());
            RecordSet getMaxid = new RecordSet();
            getMaxid.execute("select max(id) as maxid from " + dao.assetTable);
            getMaxid.next();
            int maxid = getMaxid.getInt("maxid");
            for (int i = maxid; i > maxid - paramsList_0.size(); i--) {
                dbTools.refreshRight(1, Util.getIntValue(uf_003_yyArrivalRecord_Modeid, 0), i);
            }
            logTool.writeLog("权限重构结束=>>>" + dateTools.getCurrentTimes());


        }

        return result;
    }
    */

    /**
     * 获取当前日期时间。 YYYY-MM-DD HH:MM:SS
     * @return 当前日期时间
     */
    public String getCurrDateTime() {
        Date newdate = new Date();
        long datetime = newdate.getTime();
        Timestamp timestamp = new Timestamp(datetime);
        return (timestamp.toString()).substring(0, 19);
    }

    /**
     * 获取时间戳   格式如：19990101235959
     * @return
     */
    private String getTimestamp() {
        return getCurrDateTime().replace("-", "").replace(":", "").replace(" ", "");
    }

    public String replaceStr(String str){
        //String s =  str.replace("\"","&quot;").replace("\'","&apos;")//.replace("&","&amp;")
        // .replace("<","&lt;").replace(">","&gt;");

        String s =  "<![CDATA["+str+"]]>";
        return s;
    }
}
